//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { APP_TYPE, APP_TYPE_ALL, APP_TYPE_GRPC, APP_TYPE_MONGO, APP_TYPE_MYSQL, APP_TYPE_POSTGRES, APP_TYPE_REDIS, APP_TYPE_SSH, AppInfo, list_app_by_type } from '@/api/appstore';
import { Button, List, message, Modal, Popover, Space, Table } from 'antd';
import type { GrpcServerInfo, MongoServerInfo, RedisServerInfo, SqlServerInfo, SshServerInfo, UserServerInfo } from "@/api/user_server";
import { list_server, remove_server } from "@/api/user_server";
import type { ColumnsType } from 'antd/lib/table';
import { MoreOutlined } from '@ant-design/icons';
import EditServModal from './EditServModal';
import { get_global_server_addr } from '@/api/client_cfg';
import { useStores } from '@/hooks';
import UserAppItem from '../UserAppItem';

export interface UserServerListProps {
    servType: APP_TYPE;
    dataVersion: number;
};

interface UserServerRecord {
    id: string;
    name: string;
    server_type: APP_TYPE;
    server_addr: string,
    raw_info: UserServerInfo;
    project_id: string;
}

const UserServerList = (props: UserServerListProps) => {
    const userStore = useStores("userStore");
    const projectStore = useStores("projectStore");
    const appStore = useStores("appStore");

    const [recordList, setRecordList] = useState([] as UserServerRecord[]);
    const [updateServerInfo, setUpdateServerInfo] = useState<UserServerInfo | null>(null);
    const [removeServerInfo, setRemoveServerInfo] = useState<UserServerInfo | null>(null);
    const [appInfoList, setAppInfoList] = useState([] as AppInfo[]);
    const [openServerInfo, setOpenServerInfo] = useState<UserServerInfo | null>(null);
    const [viewServerInfo, setViewServerInfo] = useState<UserServerInfo | null>(null);

    const loadRecordList = async () => {
        const tmpList = await list_server();
        const serverList: UserServerInfo[] = [];
        for (const server of tmpList) {
            if (props.servType == APP_TYPE_ALL || server.server_type == props.servType) {
                serverList.push(server);
            }
        }
        const tmpRecordList: UserServerRecord[] = [];
        for (const server of serverList) {
            let addrStr = "";
            try {
                let obj = JSON.parse(server.server_info);
                if (server.server_type == APP_TYPE_SSH) {
                    addrStr = (obj as SshServerInfo).addr;
                } else if (server.server_type == APP_TYPE_MYSQL) {
                    addrStr = (obj as SqlServerInfo).addr;
                } else if (server.server_type == APP_TYPE_POSTGRES) {
                    addrStr = (obj as SqlServerInfo).addr;
                } else if (server.server_type == APP_TYPE_MONGO) {
                    addrStr = (obj as MongoServerInfo).addrs.join(",");
                } else if (server.server_type == APP_TYPE_REDIS) {
                    addrStr = (obj as RedisServerInfo).addrs.join(",");
                } else if (server.server_type == APP_TYPE_GRPC) {
                    addrStr = (obj as GrpcServerInfo).addr;
                }
            } catch (e) {
                console.log(e);
            }
            tmpRecordList.push({
                id: server.id,
                name: server.name,
                server_type: server.server_type,
                server_addr: addrStr,
                raw_info: server,
                project_id: server.project_id ?? "",
            });
        }
        setRecordList(tmpRecordList);
    };

    const selectApp = async (serverInfo: UserServerInfo) => {
        const addr = await get_global_server_addr();
        const res = await list_app_by_type(addr, {
            app_type: serverInfo.server_type,
            session_id: userStore.sessionId,
        });
        if (res.app_info_list.length == 0) {
            message.warn("没有匹配微应用")
        } else if (res.app_info_list.length == 1) {
            appStore.openMinAppParam = {
                minAppId: res.app_info_list[0].app_id,
                extraInfo: JSON.stringify(serverInfo.server_info),
                extraInfoName: JSON.stringify(serverInfo.name),
            };
        } else {
            setOpenServerInfo(serverInfo);
            setAppInfoList(res.app_info_list);
        }
    };

    const removeServer = async () => {
        if (removeServerInfo == null) {
            return;
        }
        await remove_server(removeServerInfo.id);
        message.info("删除成功");
        setRemoveServerInfo(null);
        await loadRecordList();
    }

    const columns: ColumnsType<UserServerRecord> = [
        {
            title: "名称",
            width: 100,
            dataIndex: "name",
        },
        {
            title: "服务类型",
            width: 100,
            render: (_, row: UserServerRecord) => {
                if (row.server_type == APP_TYPE_SSH) {
                    return "SSH";
                }
                if (row.server_type == APP_TYPE_MYSQL) {
                    return "MYSQL";
                }
                if (row.server_type == APP_TYPE_POSTGRES) {
                    return "POSTGRES";
                }
                if (row.server_type == APP_TYPE_MONGO) {
                    return "MONGO";
                }
                if (row.server_type == APP_TYPE_REDIS) {
                    return "REDIS";
                }
                if (row.server_type == APP_TYPE_GRPC) {
                    return "GRPC";
                }
                return "";
            },
        },
        {
            title: "相关项目",
            width: 150,
            render: (_, row: UserServerRecord) => projectStore.getProject(row.project_id)?.basic_info.project_name ?? "",
        },
        {
            title: "连接地址",
            dataIndex: "server_addr",
        },
        {
            title: "操作",
            width: 200,
            render: (_, row: UserServerRecord) => (
                <Space>
                    <Button type="primary" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        selectApp(row.raw_info);
                    }}>访问服务</Button>
                    <Button type="link" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setUpdateServerInfo(row.raw_info);
                    }}>修改</Button>
                    <Popover placement='bottom' trigger="click" content={
                        <Space direction='vertical'>
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setViewServerInfo(row.raw_info);
                            }}>查看服务信息</Button>
                            <Button type="link" danger onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveServerInfo(row.raw_info);
                            }}>删除</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                </Space>
            )
        }
    ];

    useEffect(() => {
        loadRecordList();
    }, [props.servType, props.dataVersion]);

    return (
        <>
            <Table rowKey="id" dataSource={recordList} columns={columns} pagination={false} scroll={{ y: "calc(100vh - 270px)" }} />
            {updateServerInfo != null && (
                <EditServModal serverInfo={updateServerInfo} onCancel={() => setUpdateServerInfo(null)} onOk={() => {
                    setUpdateServerInfo(null);
                    loadRecordList();
                }} />
            )}
            {removeServerInfo != null && (
                <Modal open title="删除服务" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveServerInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeServer();
                    }}>
                    是否删除服务&nbsp;{removeServerInfo.name}&nbsp;?
                </Modal>
            )}

            {appInfoList.length > 0 && openServerInfo != null && (
                <Modal open title="微应用列表" footer={null} mask={false}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setAppInfoList([]);
                        setOpenServerInfo(null);
                    }}>
                    <List rowKey="app_id" dataSource={appInfoList} grid={{ gutter: 16 }} pagination={false}
                        renderItem={item => (
                            <List.Item>
                                <UserAppItem appInfo={item} extraInfoName={JSON.stringify(openServerInfo.name)} extraInfo={JSON.stringify(openServerInfo.server_info)} />
                            </List.Item>
                        )} />
                </Modal>
            )}
            {viewServerInfo != null && (
                <Modal open title="服务信息" footer={null} mask={false}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setViewServerInfo(null);
                    }}>
                    <pre>
                        {JSON.stringify(JSON.parse(viewServerInfo.server_info), null, 2)}
                    </pre>
                </Modal>
            )}
        </>
    );
};

export default UserServerList;